/*
 * @Author: HuRrongChao 1556810922@qq.com
 * @Date: 2024-10-08 17:02:40
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-04-18 17:00:02
 */
const api_functions = {
  getDateTransform(date) {
    const nowDate = new Date()
    const timeDiff = nowDate - date
    // 计算两个日期之间的天数
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
    // 计算两个日期之间的小时数
    const hoursDiff = Math.floor(timeDiff / (1000 * 60 * 60))
    // 计算两个日期之间的分钟数
    const minutesDiff = Math.floor(timeDiff / (1000 * 60))
    // 计算两个日期之间的秒数
    const secondsDiff = Math.floor(timeDiff / 1000)
    const year = date.getFullYear()
    const month = `${date.getMonth() + 1}`.slice(-2)
    const day = `${date.getDate()}`.slice(-2)
    if (daysDiff < 1) {
      if (minutesDiff < 1) {
        return `${secondsDiff} 秒前`
      } else if (minutesDiff < 60) {
        return `${minutesDiff} 分钟前`
      } else {
        return `${hoursDiff} 小时前`
      }
    } else if (daysDiff < 7) {
      return `${daysDiff} 天前`
    } else if (daysDiff < 31) {
      return `${Math.floor(daysDiff / 7)} 周前`
    } else if (daysDiff < 183) {
      return `${month}月${day}日`
    } else if (daysDiff < 365) {
      return `${year}年${month}月${day}日`
    } else {
      // return `${year}-${month}-${day}`
      const yearsDiff = Math.floor(daysDiff / 365)
      return `${Math.floor(yearsDiff)} 年前 | ${month}月${day}日`
    }
  },
  // 粘贴
  copyToClipboard(textToCopy) {
    return new Promise((resolve, reject) => {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        navigator.clipboard.writeText(textToCopy).then(() => {
          resolve()
        })
          .catch((error) => {
            reject(new Error('使用 Clipboard API 复制失败: ' + error.message))
          })
      } else {
        // document.execCommand('copy') 向剪贴板写文本
        const input = document.createElement('input')
        input.style.position = 'fixed'
        input.style.top = '-10000px'
        input.style.zIndex = '-999'
        document.body.appendChild(input)
        input.value = textToCopy
        input.focus()
        input.select()
        try {
          const result = document.execCommand('copy')
          document.body.removeChild(input)
          if (!result || result === 'unsuccessful') {
            reject(new Error('复制失败'))
          } else {
            resolve()
          }
        } catch (e) {
          document.body.removeChild(input)
          reject(new Error('当前浏览器不支持复制功能，请检查更新或更换其他浏览器操作'))
        }
      }
    })
  }
}

export default api_functions